package com.example.shouybl.fragment;


import android.os.Bundle;

import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.example.shouybl.BaseApp;
import com.example.shouybl.R;
import com.example.shouybl.adapter.AdPageAdapter;
import com.example.shouybl.adapter.GameAdapter;
import com.example.shouybl.adapter.GameHotAdapter;
import com.example.shouybl.bean.AppBaseBean;
import com.example.shouybl.bean.GameAd;
import com.example.shouybl.bean.GameData;
import com.example.shouybl.bean.GameHot;

import com.example.shouybl.constant.Path;
import com.example.shouybl.utils.AppAsyncTaskHelper;
import com.example.shouybl.utils.ImageLoaderUtil;
import com.example.shouybl.widget.GridViewForScrollView;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.RequestParams;
import com.loopj.android.http.TextHttpResponseHandler;
import com.nostra13.universalimageloader.core.ImageLoader;

import java.util.ArrayList;
import java.util.List;

import cz.msebera.android.httpclient.Header;

/**
 * A simple {@link Fragment} subclass.
 */
public class GameFragment extends Fragment {

    private PullToRefreshListView ptrGame;
    private ListView lvGame;
    private List<GameData> gameDatas = new ArrayList<GameData>();
    private GameAdapter gameAdapter;
    private int page = 1;

    //title布局
    private ImageView ivLeft;
    private TextView tvTitle;
    private Button btnRight;

    //头布局相关
    private View headView;
    private ViewPager vpAd;
    private AsyncHttpClient client = new AsyncHttpClient();
    //广告
    private ArrayList<ImageView> imageViews = new ArrayList<ImageView>();
    private AdPageAdapter adPageAdapter;
    private RequestParams adParams;
    private ArrayList<GameAd> gameAds = new ArrayList<GameAd>();
    //热门
    private GridViewForScrollView gvHot;
    private ArrayList<GameHot> gameHots = new ArrayList<GameHot>();
    private GameHotAdapter hotAdapter;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_game, container, false);
        //加载头布局
        addHead(inflater);
        initView(view);

        initData();
        ptrGame.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                page = 1;
                initData();
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                page++;
                initData();
            }
        });
        lvGame.setAdapter(gameAdapter);
        return view;
    }

    private void initData() {
        TypeReference<AppBaseBean<GameData>> typeReference = new TypeReference<AppBaseBean<GameData>>() {
        };
        AppAsyncTaskHelper.getInstance().post(Path.PATH_GAME, getParams(), gameDatas, ptrGame, gameAdapter, page, typeReference);
    }

    private RequestParams getParams() {
        RequestParams params = new RequestParams();
        params.add("platform", "2");
        params.add("compare", "2306d28d54c3261027a04d9049435295");
        params.add("page", String.valueOf(page));
        return params;
    }

    private void initView(View view) {
        //主体变量
        ptrGame = (PullToRefreshListView) view.findViewById(R.id.ptr_game);
        ptrGame.setMode(PullToRefreshBase.Mode.BOTH);
        lvGame = ptrGame.getRefreshableView();
        gameAdapter = new GameAdapter(gameDatas, BaseApp.getInstance());
        ptrGame.getRefreshableView().addHeaderView(headView);
        //title变量
        ivLeft = (ImageView) view.findViewById(R.id.iv_left);
        tvTitle = (TextView) view.findViewById(R.id.tv_title);
        btnRight = (Button) view.findViewById(R.id.btn_right);
        tvTitle.setText("搜索游戏");
        btnRight.setText("请登录");

    }

    //头布局
    private void addHead(LayoutInflater inflater) {
        headView = inflater.inflate(R.layout.item_add_game_layout, null);
        initAd();
        initHot();
    }

    //热门推荐数据
    private void initHot() {
        gvHot = (GridViewForScrollView) headView.findViewById(R.id.game_head_hot_gv);
        hotAdapter = new GameHotAdapter(gameHots, BaseApp.getInstance());
        gvHot.setAdapter(hotAdapter);
        client.post(Path.PATH_GAME_HOT, grtHotParams(), new TextHttpResponseHandler() {
            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {

            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String responseString) {
                TypeReference<AppBaseBean<GameHot>> type = new TypeReference<AppBaseBean<GameHot>>() {};
                AppBaseBean bean=JSONObject.parseObject(responseString,type);
                if (bean!=null&&bean.getState().equals("success")){
                    gameHots.addAll(bean.getInfo());
                }
                hotAdapter.notifyDataSetChanged();
            }
        });
    }

    private RequestParams grtHotParams() {
        RequestParams params = new RequestParams();
        params.add("platform", "2");
        params.add("compare", "84e3eeaeb16f8bcb549e2618fce9bd2b");
        return params;
    }

    //广告数据
    private void initAd() {
        vpAd = (ViewPager) headView.findViewById(R.id.game_head_viewpager);
        adPageAdapter = new AdPageAdapter(imageViews);
        vpAd.setAdapter(adPageAdapter);
        client.post(Path.PATH_GAME_AD, getAdParams(), new TextHttpResponseHandler() {
            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {

            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String responseString) {
                TypeReference<AppBaseBean<GameAd>> typeReference = new TypeReference<AppBaseBean<GameAd>>() {
                };
                AppBaseBean bean = JSONObject.parseObject(responseString, typeReference);
                if (bean != null && bean.getState().equals("success")) {
                    gameAds.addAll(bean.getInfo());
                }
                for (int i = 0; i < gameAds.size(); i++) {
                    ImageView iv = new ImageView(getActivity());
                    iv.setScaleType(ImageView.ScaleType.CENTER_CROP);
                    ImageLoader.getInstance().displayImage(gameAds.get(i).getBimg(), iv, ImageLoaderUtil.getDefaultOptions());
                    imageViews.add(iv);
                }
                adPageAdapter.notifyDataSetChanged();
            }
        });
    }

    public RequestParams getAdParams() {
        RequestParams params = new RequestParams();
        params.add("platform", "2");
        params.add("compare", "2306d28d54c3261027a04d9049435295");
        params.add("pos", "3");
        return adParams;
    }
}
